import React, { useState, useCallback } from 'react';
import { ColorPickerProps } from '@/types/components';
import { ColorUtils } from '@/utils/color';
import { Input } from '../ui/Input';

export const ColorPicker: React.FC<ColorPickerProps> = ({
  value,
  onChange,
  mode,
  showPresets = true,
  disabled = false,
  className = ''
}) => {
  const [localValue, setLocalValue] = useState(value);
  const [isValidColor, setIsValidColor] = useState(true);

  // 预设颜色
  const presetColors = [
    '#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF',
    '#000000', '#FFFFFF', '#808080', '#FFA500', '#800080', '#FFC0CB',
    '#A52A2A', '#008000', '#000080', '#FFD700', '#C0C0C0', '#FF6347'
  ];

  const handleColorChange = useCallback((newValue: string) => {
    setLocalValue(newValue);
    
    try {
      let color;
      
      switch (mode) {
        case 'hex':
          if (ColorUtils.isValidHex(newValue)) {
            color = ColorUtils.fromHex(newValue);
            setIsValidColor(true);
            onChange(newValue);
          } else {
            setIsValidColor(false);
          }
          break;
          
        case 'rgb':
          // RGB模式下的处理逻辑
          const rgbMatch = newValue.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
          if (rgbMatch) {
            const [, r, g, b] = rgbMatch.map(Number);
            if (ColorUtils.isValidRgb(r, g, b)) {
              color = ColorUtils.fromRgb(r, g, b);
              setIsValidColor(true);
              onChange(color.hex);
            } else {
              setIsValidColor(false);
            }
          } else {
            setIsValidColor(false);
          }
          break;
          
        case 'hsl':
          // HSL模式下的处理逻辑
          const hslMatch = newValue.match(/hsl\((\d+),\s*(\d+)%,\s*(\d+)%\)/);
          if (hslMatch) {
            const [, h, s, l] = hslMatch.map(Number);
            if (ColorUtils.isValidHsl(h, s, l)) {
              color = ColorUtils.fromHsl(h, s, l);
              setIsValidColor(true);
              onChange(color.hex);
            } else {
              setIsValidColor(false);
            }
          } else {
            setIsValidColor(false);
          }
          break;
          
        case 'hsv':
          // HSV模式下的处理逻辑
          const hsvMatch = newValue.match(/hsv\((\d+),\s*(\d+)%,\s*(\d+)%\)/);
          if (hsvMatch) {
            const [, h, s, v] = hsvMatch.map(Number);
            if (h >= 0 && h <= 360 && s >= 0 && s <= 100 && v >= 0 && v <= 100) {
              color = ColorUtils.fromHsv(h, s, v);
              setIsValidColor(true);
              onChange(color.hex);
            } else {
              setIsValidColor(false);
            }
          } else {
            setIsValidColor(false);
          }
          break;
      }
    } catch (error) {
      setIsValidColor(false);
    }
  }, [mode, onChange]);

  const handlePresetClick = useCallback((presetColor: string) => {
    setLocalValue(presetColor);
    setIsValidColor(true);
    onChange(presetColor);
  }, [onChange]);

  const getDisplayValue = () => {
    if (!ColorUtils.isValidHex(value)) return value;
    
    const color = ColorUtils.fromHex(value);
    
    switch (mode) {
      case 'rgb':
        return `rgb(${color.rgb.r}, ${color.rgb.g}, ${color.rgb.b})`;
      case 'hsl':
        return `hsl(${color.hsl.h}, ${color.hsl.s}%, ${color.hsl.l}%)`;
      case 'hsv':
        return `hsv(${color.hsv.h}, ${color.hsv.s}%, ${color.hsv.v}%)`;
      default:
        return color.hex;
    }
  };

  const getPlaceholder = () => {
    switch (mode) {
      case 'rgb':
        return 'rgb(255, 0, 0)';
      case 'hsl':
        return 'hsl(0, 100%, 50%)';
      case 'hsv':
        return 'hsv(0, 100%, 100%)';
      default:
        return '#FF0000';
    }
  };

  return (
    <div className={`space-y-4 ${className}`}>
      {/* 颜色输入区域 */}
      <div className="flex items-center space-x-3">
        {/* 颜色预览 */}
        <div
          className="w-12 h-12 border border-gray-300 rounded-lg cursor-pointer"
          style={{ backgroundColor: ColorUtils.isValidHex(value) ? value : '#ffffff' }}
          title="点击选择颜色"
        >
          <input
            type="color"
            value={ColorUtils.isValidHex(value) ? value : '#ffffff'}
            onChange={(e) => handleColorChange(e.target.value)}
            disabled={disabled}
            className="w-full h-full opacity-0 cursor-pointer"
          />
        </div>

        {/* 颜色值输入 */}
        <div className="flex-1">
          <Input
            value={localValue || getDisplayValue()}
            onChange={handleColorChange}
            placeholder={getPlaceholder()}
            disabled={disabled}
            error={!isValidColor ? '无效的颜色格式' : undefined}
          />
        </div>
      </div>

      {/* RGB滑块（高级模式） */}
      {mode === 'rgb' && ColorUtils.isValidHex(value) && (
        <RGBSliders
          color={ColorUtils.fromHex(value)}
          onChange={(color) => onChange(color.hex)}
          disabled={disabled}
        />
      )}

      {/* HSL滑块（高级模式） */}
      {mode === 'hsl' && ColorUtils.isValidHex(value) && (
        <HSLSliders
          color={ColorUtils.fromHex(value)}
          onChange={(color) => onChange(color.hex)}
          disabled={disabled}
        />
      )}

      {/* 预设颜色 */}
      {showPresets && (
        <div className="space-y-2">
          <label className="block text-sm font-medium text-gray-700">
            预设颜色
          </label>
          <div className="grid grid-cols-6 gap-2">
            {presetColors.map((color, index) => (
              <button
                key={index}
                className={`w-8 h-8 rounded border-2 transition-transform hover:scale-110 ${
                  value === color ? 'border-blue-500' : 'border-gray-300'
                }`}
                style={{ backgroundColor: color }}
                onClick={() => handlePresetClick(color)}
                disabled={disabled}
                title={color}
              />
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

// RGB滑块组件
const RGBSliders: React.FC<{
  color: any;
  onChange: (color: any) => void;
  disabled: boolean;
}> = ({ color, onChange, disabled }) => {
  const handleRGBChange = (component: 'r' | 'g' | 'b', value: number) => {
    const newRgb = { ...color.rgb, [component]: value };
    const newColor = ColorUtils.fromRgb(newRgb.r, newRgb.g, newRgb.b);
    onChange(newColor);
  };

  return (
    <div className="space-y-3">
      <div className="flex items-center space-x-3">
        <label className="w-8 text-sm font-medium text-red-600">R</label>
        <input
          type="range"
          min="0"
          max="255"
          value={color.rgb.r}
          onChange={(e) => handleRGBChange('r', parseInt(e.target.value))}
          disabled={disabled}
          className="flex-1"
        />
        <span className="w-12 text-sm text-gray-700">{color.rgb.r}</span>
      </div>
      <div className="flex items-center space-x-3">
        <label className="w-8 text-sm font-medium text-green-600">G</label>
        <input
          type="range"
          min="0"
          max="255"
          value={color.rgb.g}
          onChange={(e) => handleRGBChange('g', parseInt(e.target.value))}
          disabled={disabled}
          className="flex-1"
        />
        <span className="w-12 text-sm text-gray-700">{color.rgb.g}</span>
      </div>
      <div className="flex items-center space-x-3">
        <label className="w-8 text-sm font-medium text-blue-600">B</label>
        <input
          type="range"
          min="0"
          max="255"
          value={color.rgb.b}
          onChange={(e) => handleRGBChange('b', parseInt(e.target.value))}
          disabled={disabled}
          className="flex-1"
        />
        <span className="w-12 text-sm text-gray-700">{color.rgb.b}</span>
      </div>
    </div>
  );
};

// HSL滑块组件
const HSLSliders: React.FC<{
  color: any;
  onChange: (color: any) => void;
  disabled: boolean;
}> = ({ color, onChange, disabled }) => {
  const handleHSLChange = (component: 'h' | 's' | 'l', value: number) => {
    const newHsl = { ...color.hsl, [component]: value };
    const newColor = ColorUtils.fromHsl(newHsl.h, newHsl.s, newHsl.l);
    onChange(newColor);
  };

  return (
    <div className="space-y-3">
      <div className="flex items-center space-x-3">
        <label className="w-8 text-sm font-medium text-purple-600">H</label>
        <input
          type="range"
          min="0"
          max="360"
          value={color.hsl.h}
          onChange={(e) => handleHSLChange('h', parseInt(e.target.value))}
          disabled={disabled}
          className="flex-1"
        />
        <span className="w-12 text-sm text-gray-700">{color.hsl.h}°</span>
      </div>
      <div className="flex items-center space-x-3">
        <label className="w-8 text-sm font-medium text-orange-600">S</label>
        <input
          type="range"
          min="0"
          max="100"
          value={color.hsl.s}
          onChange={(e) => handleHSLChange('s', parseInt(e.target.value))}
          disabled={disabled}
          className="flex-1"
        />
        <span className="w-12 text-sm text-gray-700">{color.hsl.s}%</span>
      </div>
      <div className="flex items-center space-x-3">
        <label className="w-8 text-sm font-medium text-gray-600">L</label>
        <input
          type="range"
          min="0"
          max="100"
          value={color.hsl.l}
          onChange={(e) => handleHSLChange('l', parseInt(e.target.value))}
          disabled={disabled}
          className="flex-1"
        />
        <span className="w-12 text-sm text-gray-700">{color.hsl.l}%</span>
      </div>
    </div>
  );
};